package com.xilihui.xlh.business.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;


import com.weigan.loopview.LoopView;
import com.weigan.loopview.OnItemSelectedListener;
import com.xilihui.xlh.R;
import com.xilihui.xlh.core.util.ScreenUtil;

import java.util.List;

/**
 * 通用PickerViewDialog
 * 2017/2/16.
 */

public abstract class PickerViewDialog<T> {

    private Context context;

    private Dialog dialog;

    private List<T> list;

    private T t;

    private int pos;

    /**
     * @param context
     * @param list
     * @param lastPosition 上一次选中位置
     */
    public PickerViewDialog(Context context, List<T> list, int lastPosition) {
        this.context = context;
        this.list = list;
        pos = lastPosition;
        if (!list.isEmpty())
            t = list.get(lastPosition);
    }

    protected abstract void setItems(LoopView loopView, List<T> list);

    protected abstract void onConfirm(T t, int position);

    public void show() {

        if (list.isEmpty()) {
            return;
        }

        dialog = new Dialog(context, R.style.Dialog);
        dialog.setContentView(R.layout.dialog_single_pick_view);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.setCanceledOnTouchOutside(true);
        setMatchWidth();
        initView(list);
        dialog.show();
    }

    private void initView(final List<T> list) {

        dialog.findViewById(R.id.tvConfirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 确定
                onConfirm(t, pos);
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.tvCancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        LoopView loopView = (LoopView) dialog.findViewById(R.id.loopView);
        // 处理数据
        setItems(loopView, list);
        // 设置当前数据
        loopView.setCurrentPosition(pos);
        loopView.setNotLoop();
        loopView.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                t = list.get(index);
                pos = index;
            }
        });
    }

    private void setMatchWidth() {
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = ScreenUtil.getScreenWidth(context);
        lp.height = (int) (ScreenUtil.getScreenHeight(context) * 0.4);
        dialog.getWindow().setAttributes(lp);
    }
}
